package com.blink.zookeeper.operate;

import com.blink.base.TestZK;
import com.blink.zookeeper.ZooKeeperCreator;
import org.apache.zookeeper.*;
import org.junit.jupiter.api.Test;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * <Description> 创建节点：不支持递归创建</Description>
 * <ClassName> TestZKCreateNode</ClassName>
 *
 * @Author liuxianzhao
 * @Date 2018年01月12日 13:40
 */
public class TestZKCreateNode extends TestZK {
    /**
     * <Title>testZkCreateNodeSync</Title>
     * <Description> 同步创建节点</Description>
     *
     * @return void
     * @throws
     */
    @Test
    public void testZkCreateNodeSync() throws KeeperException, InterruptedException {
        //创建zk
        ZooKeeper zk = ZooKeeperCreator.getZk("testZkCreateNodeSync");
        String result = zk.create("/NODE",
                "同步创建节点".getBytes(StandardCharsets.UTF_8),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL);
        logger.info("创建临时节点：{},完毕", result);
        result = zk.create("/NODE",
                "同步创建节点".getBytes(StandardCharsets.UTF_8),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL_SEQUENTIAL);
        logger.info("创建临时有序节点：{},完毕", result);
        TimeUnit.MINUTES.sleep(1);
        zk.close();
    }


    /**
     * <Title>testZkCreateNodeAsync</Title>
     * <Description> 异步创建节点</Description>
     *
     * @return void
     * @throws
     */
    @Test
    public void testZkCreateNodeAsync() throws KeeperException, InterruptedException {
        ZooKeeper zk = ZooKeeperCreator.getZk("testZkCreateNodeAsync");
        zk.create("/NODE1",
                "异步创建节点".getBytes(StandardCharsets.UTF_8),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL,
                new DefaultStringCallback(),
                "testCTX");
        zk.create("/NODE1",
                "异步创建节点".getBytes(StandardCharsets.UTF_8),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL,
                new DefaultStringCallback(),
                "testCTX");
        zk.create("/NODE2",
                "异步创建节点".getBytes(StandardCharsets.UTF_8),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL_SEQUENTIAL,
                new DefaultStringCallback(),
                "testCTX");
        TimeUnit.MINUTES.sleep(1);
        zk.close();
    }


    class DefaultStringCallback implements AsyncCallback.StringCallback {
        @Override
        public void processResult(int rc, String path, Object ctx, String name) {
            if (KeeperException.Code.OK.intValue() == rc) {
                logger.info("创建成功: path-{},name-{},ctx-{}", path, name, ctx);
            } else {
                logger.error("创建失败:" + KeeperException.create(KeeperException.Code.get(rc), path).getMessage());
            }
        }
    }
}
